package algorithms;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.ObjectInputStream;

import evaluation.Measure;

//import weka.classifiers.functions.LibSVM;
import util.Utils;
import weka.classifiers.functions.LibSVM; // use weka version 3.6
import weka.classifiers.Classifier;
import weka.core.*;

public class SVM {

	public static Classifier getInstance() throws Exception {
		
		LibSVM svm = new LibSVM();
		
		return svm;
	}
	
   public static Classifier buildModel(String data, String model) throws Exception {
		
	    LibSVM svm = new LibSVM();
		Classifier cls = (Classifier) svm;
		
		BufferedReader reader = new BufferedReader(
                new FileReader(data));
		
		Instances instances = new Instances(reader);
		instances.setClassIndex(instances.numAttributes() - 1);
		cls.buildClassifier(instances);
		
		weka.core.SerializationHelper.write(model, cls);
		
		return svm;
	}
	
	public static Classifier loadModel(String model) throws Exception {
		
		ObjectInputStream ois = new ObjectInputStream(
				new FileInputStream(model));
		Classifier cls = (Classifier) weka.core.SerializationHelper.read(model);
		ois.close();
	    LibSVM svm = (LibSVM) cls;
		return svm;
	}
	
	public static void main(String[] args)throws Exception{
		String datafile = "/home/runxin/workspace/Network/data/m_moore/entry10.arff";
		Instances dataset = Utils.getInstances(datafile);
		String save = "data/models/svm10.model";
		LibSVM learner = new LibSVM();
		learner.buildClassifier(dataset);
		Measure mea = new Measure(dataset);
		mea.evaluate(learner);
		weka.core.SerializationHelper.write(save, learner);
		
	}
	
	
}
